package main

import (
    "fmt"
    "gitee.com/HyoJoo-W/ChatRoom/common/message"
    "gitee.com/HyoJoo-W/ChatRoom/server/process"
    "gitee.com/HyoJoo-W/ChatRoom/server/utils"
    "io"
    "net"
)

type Processor struct {
    Conn net.Conn
}

//根据客户端发送的消息类型，分发处理函数
func (this *Processor) serverProcessMes(mes *message.Message) (err error) {
    switch mes.Type {
    case message.LoginMesType:
        //处理登录
        //创建UserProcess实例
        up := &process.UserProcess{
            Conn: this.Conn,
        }
        err = up.ServerProcessLogin(mes)
    case message.RegisterMesType:
        //处理注册
        up := &process.UserProcess{
            Conn: this.Conn,
        }
        err = up.ServerProcessRegister(mes)
    case message.SmsMesType:
        //转发群聊消息
        smsProcess := &process.SmsProcess{}
        smsProcess.SendGroupMes(mes)
    default:
        fmt.Println("消息类型不存在,无法处理")
    }
    return
}

//总控程序,处理客户端请求
func (this *Processor) processMessage() (err error) {
    //循环读客户端发送的信息
    for {
        //封装读取客户端数据
        //创建transfer实例
        tf := &utils.Transfer{
            Conn: this.Conn,
        }
        mes, err := tf.ReadPkg()
        if err != nil {
            if err == io.EOF {
                fmt.Println("客户端退出，服务器端退出")
                return err
            } else {
                fmt.Println("readPkg err = ", err)
                return err
            }
        }
        //根据客户端请求消息类型分发处理
        err = this.serverProcessMes(&mes)
        if err != nil {
            return err
        }
    }
}
